AP Computer Science A - Student-Friendly Walkthrough
DogWalker class:
walkDogs(int hour)dogWalkShift(int startHour, int endHour)Your job is to read the directions carefully and turn them into Java code.
private int maxDogs;
private DogWalkCompany company;
These variables mean:
The company gives us two helpful methods:
company.numAvailableDogs(hour) → tells how many dogs are available that hourcompany.updateDogs(hour, dogsWalked) → updates the company after dogs are takenThis method should figure out how many dogs the walker can walk during one specific hour.
maxDogsmaxDogs.| Available Dogs | maxDogs | Dogs Walked |
|---|---|---|
| 10 | 4 | 4 |
| 3 | 4 | 3 |
public int walkDogs(int hour)
{
int available = company.numAvailableDogs(hour);
int dogsWalked = Math.min(available, maxDogs);
company.updateDogs(hour, dogsWalked);
return dogsWalked;
}
available stores the number of dogs ready to be walked.Math.min(available, maxDogs) chooses the smaller number.updateDogs makes sure those dogs are no longer counted as available.company.updateDogs(hour, dogsWalked)available instead of the smaller valuemaxDogs limitThis method calculates how much money the walker earns during an entire shift.
For each hour in the shift:
walkDogs(hour)maxDogs dogs, orstartHour to endHour, inclusive.walkDogs(hour).dogsWalked * 5 to the total.
public int dogWalkShift(int startHour, int endHour)
{
int total = 0;
for (int hour = startHour; hour <= endHour; hour++)
{
int dogsWalked = walkDogs(hour);
total += dogsWalked * 5;
if (dogsWalked == maxDogs || (hour >= 9 && hour <= 17))
{
total += 3;
}
}
return total;
}
walkDogs(hour) handles the dog-counting logic from Part A.< instead of <= in the loopwalkDogs(hour)
if (dogsWalked == maxDogs)
total += 3;
if (hour >= 9 && hour <= 17)
total += 3;
This is wrong because the prompt only gives one $3 bonus per hour, not two.
public int walkDogs(int hour)
{
int available = company.numAvailableDogs(hour);
int dogsWalked = Math.min(available, maxDogs);
company.updateDogs(hour, dogsWalked);
return dogsWalked;
}
public int dogWalkShift(int startHour, int endHour)
{
int total = 0;
for (int hour = startHour; hour <= endHour; hour++)
{
int dogsWalked = walkDogs(hour);
total += dogsWalked * 5;
if (dogsWalked == maxDogs || (hour >= 9 && hour <= 17))
{
total += 3;
}
}
return total;
}